package com.kgc.sbt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kgc.sbt.beans.Sign;
import com.kgc.sbt.beans.UserLogin;
import com.kgc.sbt.config.annotation.RequestPermission;
import com.kgc.sbt.config.annotation.RequestUser;
import com.kgc.sbt.service.BuyVipService;
import com.kgc.sbt.service.UserService;

import com.kgc.sbt.utils.*;
import io.swagger.annotations.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * Created on 2021/8/18.
 * <p>
 * Author: 190120
 * <p>
 * Description: 用户登陆注册操作入口
 */
@RestController
@Api(tags = " 1 用户登录注册操作入口")
@Slf4j
public class UserLoginController {

    @Value("${wechat.auth.appId}")
    private String appId;

    @Value("${wechat.auth.appSecret}")
    private String appSecret;

    @Value("${wechat.auth.codeUri}")
    private String codeUri;

    @Value("${wechat.auth.redirectUri}")
    private String redirectUri;

    @Value("${wechat.auth.accessTokenUri}")
    private String accessTokenUri;

    @Value("${wechat.auth.userInfoUri}")
    private String userInfoUri;

    @Value("${wechat.auth.refreshTokenUri}")
    private String refreshTokenUri;

    @Value("${wechat.auth.authUri}")
    private String authUri;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserService userService;

    @Autowired
    private BuyVipService buyVipService;

    /**
     * @return :
     * @author : 190120
     * @date : 2021/7/29
     * @description :  添加一个获取收集验证码的入口，浏览器输入手机号，点击获取验证码，将该手机的验证码存入redis，有效期是60s(在有效期内，使用该验证码可以返回该验证码正确或错误，否则超时提示验证码失效，需要重新获取)
     */
    //发送验证码
    @PostMapping("/sendCode")
    @ApiOperation(value = "发送验证码", notes = "获取验证码并根据手机发送验证码")
    @ApiResponses({
            @ApiResponse(code = 0000, message = "发送验证码成功"),
            @ApiResponse(code = 1001, message = "发送验证码失败")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "注册手机号", required = true),
    })
    RequestResult<Map<String, Object>> sendCode(String phone) {
        return userService.sendCode(phone);
    }


    /**
     * @return
     * @author 190120
     * @date 2021/6/21
     * @descrption： 用户手机验证码注册
     */
    @PostMapping("/register")
    @ApiOperation(value = "手机验证码注册", notes = "支持用户使用手机号和密码进行登录")
    @ApiResponses({
            @ApiResponse(code = 8848, message = "手机号非法"),
            @ApiResponse(code = 8748, message = "手机号未填写正确或验证码已失效"),
            @ApiResponse(code = 8648, message = "验证码错误，请重试！"),
            @ApiResponse(code = 8548, message = "该手机已被注册！")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "请填写注册手机号", required = true),
            @ApiImplicitParam(name = "code", value = "输入收到的验证码", required = true),
            @ApiImplicitParam(name = "password", required = true, value = "密码"),
            @ApiImplicitParam(name = "userName", required = true, value = "用户名")
    })
    public RequestResult<String> register(@RequestParam String phone, @RequestParam String code, @RequestParam String password, @RequestParam String userName) {
        //如果用户获取过验证码还没有失效，就直接将之前生成的重新发送
        if (!ObjectUtils.isEmpty(userService.queryByPhone(phone))) {
            return ResultBuildUtil.fail("8548", " 该手机已被注册!");
        }
        // 校验手机号是否正确
        if (phone.length() != 11) {
            return ResultBuildUtil.fail("8848", "手机号非法，请重新输入");
        }
        log.info("------ 根据手机号{},获取验证码 ------", phone);
        // 校验验证码是否失效
        if (!redisUtils.hasKey(phone)) {
            log.info("------手机号{},验证码失效 ------", phone);
            return ResultBuildUtil.fail("8748", "手机号未填写正确或验证码已失效");
        }
        // 校验验证码是否正确
        if (!code.equals(redisUtils.get(phone).toString())) {
            log.info("------手机号{},验证码错误，当前验证码{}，系统验证码{} ------", phone, code, redisUtils.get(phone));
            return ResultBuildUtil.fail("8648", "验证码错误，请重试！");
        }


        userService.insertUser(phone, password, userName);

        UserLogin u = userService.queryByPhone(phone);

        if (userService.queryVipByUserId(u.getUserId())) {
            userService.insertVipByUserId(u.getUserId());
        }

        // 注册成功后，删除验证码
        redisUtils.del(phone);
        // 返回成功的结果
        return ResultBuildUtil.success("注册成功！，欢迎用户：" + userName);


    }

    /**
     * @return :
     * @author : 190120
     * @date : 2021/8/6
     * @description :  请求微信公众号测试平台，通过用户授权，获取code值
     * 注意：code不是同步接口返回的，而是异步提供的回调地址，进行回调
     */
    @GetMapping("/gainCodeUrl")
    @ApiOperation(value = "微信登录授权 ")
    @ApiResponses({
            @ApiResponse(code = 5658, message = "用户已经登录，无需再次登录")
    })
    public RequestResult<String> wechatAuthCode(HttpServletRequest request) {
        String token1 = request.getHeader("token");
        Integer userId = (Integer) redisUtils.get(token1);
        if (null != userService.queryUserByUserId(userId)) {
            log.info("------ 用户已经登录，无需再次登录 ------");
            return ResultBuildUtil.fail("5658", "用户已经登录，无需再次登录");
        }

        //根据官方示例，生成请求访问地址
        //官方示例：https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
        StringBuffer sbf = new StringBuffer(codeUri);
        sbf.append("?appid=").append(appId)
                .append("&redirect_uri=").append(redirectUri)
                .append("&response_type=code")
                .append("&scope=snsapi_userinfo")
                .append("&state=STATE#wechat_redirect");
        //返回请求地址
        return ResultBuildUtil.success(sbf.toString());
    }

    /**
     * @return :
     * @author : 190120
     * @date : 2021/8/6
     * @description : 接受微信官方回调的code值，需要根据此code换取access_token
     */
    @GetMapping("/backCode")
    @ApiIgnore
    public RequestResult<String> wechatAuthBackCode(HttpServletRequest request) {

        //微信官方回调的示例  redirect_uri/?code=CODE&state=STATE。
        //code说明 ： code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
        //获取code值
        String backCode = request.getParameter("code");
        log.info("------ 2 微信官方回调的code值：{} ------", backCode);
        //验证code是否合法
        if (StringUtils.isEmpty(backCode)) {
            log.error("------ 微信回调code非法 ------");
            return ResultBuildUtil.fail("10001", "微信回调code为空");
        }

        //通过获取的code值，到微信官方换取access_token
        //官方的请求实例： https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        //注意：由于公众号的secret和获取到的access_token安全级别都非常高，必须只保存在服务器，不允许传给客户端。后续刷新access_token、通过access_token获取用户信息等步骤，也必须从服务器发起。
        //生成访问的完整请求地址
        StringBuffer sbf = new StringBuffer(accessTokenUri);
        sbf.append("?appid=").append(appId)
                .append("&secret=").append(appSecret)
                .append("&code=").append(backCode)
                .append("&grant_type=authorization_code");
        log.info("------ 3通过回调的code值，请求微信官方测试平台，换取access_token,请求地址：{} ------", sbf.toString());

        // 根据请求地址，访问获取access_token,注意，此处是同步返回的，不是异步
        // 返回的内容是json字符串，官方正确实例：{"access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
        //通过程序发送http请求
        String backDetail = HttpClient4Util.getResponse4GetAsString(sbf.toString(), "utf-8");

        log.info("------ 4 请求微信官方测试平台，换取access_token,同步返回结果：{} ------", backDetail);

        //解析返回的json字符串，获取拉取用户信息，需要的access_token
        JSONObject jsonObject = JSON.parseObject(backDetail);

        // 是否返回正确结果
        if (!StringUtils.isEmpty(jsonObject.getString("errcode"))) {
            return ResultBuildUtil.fail(jsonObject.getString("errcode"), jsonObject.getString("errmsg"));
        }
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");


        //如果网页授权作用域为snsapi_userinfo，则此时开发者可以通过access_token和openid拉取用户信息了。
        //请求方法
        StringBuffer pulluserInfoUrl = new StringBuffer(userInfoUri);
        pulluserInfoUrl.append("?access_token=").append(accessToken)
                .append("&openid=").append(openId)
                .append("&lang=zh_CN");
        String userInfo = HttpClient4Util.getResponse4GetAsString(pulluserInfoUrl.toString(), "utf-8");
        if (ObjectUtils.isEmpty(userService.queryByOpenId(openId))) {
            log.info("------ 微信验证成功，请去绑定手机号，openId：{}------", openId);
            redisUtils.set("openId", openId, 1800);
            return ResultBuildUtil.success("微信验证成功，请去绑定手机号,微信用户信息为：" + userInfo);
        } else {
            UserLogin user = userService.queryByOpenId(openId);
            String token = UUID.randomUUID().toString();

            userService.saveToken(token, user.getUserId());
            // redis中存入token
            redisUtils.set("token", token, 1800);
            // redis中将token值当作key去存userId
            redisUtils.set(token, user.getUserId(), 1800);

            log.info("------用户登陆成功，手机号为：{}，用户信息为：{}，登录token为:{}", user.getUserPhone(), userInfo, token);
            return ResultBuildUtil.success("登录成功！用户手机号为:" + user.getUserPhone() + ";微信用户信息为:" + userInfo + "登录token值是=" + token);
        }
    }

    @GetMapping("/wechatBinding")
    @ApiOperation(value = "微信绑定手机号")
    @ApiImplicitParam(name = "phoneNo", required = true, value = "手机号")
    public RequestResult<Map<String, String>> wechatBinding(@RequestParam String phoneNo) {
        if (!redisUtils.hasKey("openId")) {
            return ResultBuildUtil.fail("6668", "微信还未授权！！");
        }
        String openId = redisUtils.get("openId").toString();
        if (ObjectUtils.isEmpty(userService.queryByOpenId(openId))) {
            if (ObjectUtils.isEmpty(userService.queryByPhone(phoneNo))) {
                return ResultBuildUtil.fail("6665", "该手机号未注册过，请前往注册账号");
            } else {
                if (StringUtils.isEmpty(userService.queryByPhone(phoneNo).getOpenId())) {
                    // 为用添加openid
                    userService.updateUserByPhone(phoneNo, openId);
                    String token = UUID.randomUUID().toString();

                    // 绑定手机号时添加token
                    userService.saveToken(token, userService.queryByPhone(phoneNo).getUserId());
                    redisUtils.set(token, userService.queryByPhone(phoneNo).getUserId());

                    Map<String, String> data = new HashMap<>();
                    data.put("msg", "该用户微信与手机号:"+phoneNo+"绑定成功");
                    data.put("token:", token);
                    return ResultBuildUtil.success(data);
                }
                return ResultBuildUtil.fail("6664", "该手机号已经绑定微信，绑定失败！");
            }
        }
        return ResultBuildUtil.fail("6663", "该微信已绑定过手机号，绑定失败");
    }

    /**
     * @return
     * @author 190120
     * @date 2021/6/21
     * @descrption： 使用密码登录
     */
    @GetMapping("/loginUsePwd")
    @ApiOperation(value = "使用密码登录", notes = "支持用户使用手机号和密码进行登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", required = true, value = "请填写手机号"),
            @ApiImplicitParam(name = "password", required = true, value = "请输入密码")
    })
    @ApiResponses({
            @ApiResponse(code = 6665, message = "该手机号未注册过，请前往注册账号"),
            @ApiResponse(code = 4002, message = "密码错误，请重新输入！"),
            @ApiResponse(code = 5658, message = "用户已经登录，无需再次登录"),
            @ApiResponse(code = 8848, message = "手机号非法，请重新输入")
    })
    public RequestResult<Map<String, Object>> login(HttpServletRequest request, @RequestParam String phone, @RequestParam String password) {
        String token1 = request.getHeader("token");
        Integer userId = (Integer) redisUtils.get(token1);
        if (null != userService.queryUserByUserId(userId)) {
            log.info("------ 用户已经登录，无需再次登录 ------");
            return ResultBuildUtil.fail("5658", "用户已经登录，无需再次登录");
        }

        Map<String, Object> data = new HashMap<>();
        // 校验手机号是否正确
        if (phone.length() != 11 || !isAllNumer(phone)) {
            return ResultBuildUtil.fail("8848", "手机号非法，请重新输入");
        }
        //判断数据库中是否存在该手机用户
        if (ObjectUtils.isEmpty(userService.queryByPhone(phone))) {
            return ResultBuildUtil.fail("6665", "该手机号未注册过，请前往注册账号");
        } else {
            UserLogin user = userService.queryByPhone(phone);
            String pwd = user.getUserPassword();
            String userName = user.getUserName();
            //将页面传来的password加密
            password = EncodeUtils.testDigest(password);
            if (!pwd.equals(password)) {
                return ResultBuildUtil.fail("4002", "密码错误，请重新输入！");
            }
            String token = UUID.randomUUID().toString();
            userService.saveToken(token, user.getUserId());

            redisUtils.set(token, user.getUserId());
            data.put("token", token);
            data.put("msg", "登陆成功,欢迎用户:" + userName);
            return ResultBuildUtil.success(data);
        }
    }

    /**
     * @return
     * @author 190120
     * @date 2021/6/21
     * @descrption： 使用验证码登录
     */
    @GetMapping("/loginUserCode")
    @ApiOperation(value = "使用验证码登录", notes = "支持用户使用手机号和验证码进行登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", required = true, value = "手机号"),
            @ApiImplicitParam(name = "code", required = true, value = "验证码")
    })
    @ApiResponses({
            @ApiResponse(code = 6665, message = "该手机号未注册过，请前往注册账号"),
            @ApiResponse(code = 4002, message = "密码错误，请重新输入！"),
            @ApiResponse(code = 5658, message = "用户已经登录，无需再次登录"),
            @ApiResponse(code = 8848, message = "手机号非法，请重新输入")
    })
    public RequestResult<Map<String, Object>> loginUseVerifyCode(HttpServletRequest request, @RequestParam String phone, @RequestParam String code) {
        String token1 = request.getHeader("token");
        Integer userId = (Integer) redisUtils.get(token1);
        if (null != userService.queryUserByUserId(userId)) {
            log.info("------ 用户已经登录，无需再次登录 ------");
            return ResultBuildUtil.fail("5658", "用户已经登录，无需再次登录");
        }

        Map<String, Object> data = new HashMap<>();
        // 校验手机号是否正确
        if (phone.length() != 11 || !isAllNumer(phone)) {
            return ResultBuildUtil.fail("8848", "手机号非法，请重新输入");
        }
        // 校验验证码是否失效
        if (!redisUtils.hasKey(phone)) {
            log.info("------手机号{},验证码失效 ------", phone);
            return ResultBuildUtil.fail("8748", "手机号未填写正确或验证码已失效");
        }
        //判断数据库中是否存在该手机用户
        if (ObjectUtils.isEmpty(userService.queryByPhone(phone))) {
            return ResultBuildUtil.fail("6665", "该手机号未注册过，请前往注册账号");
        } else {
            // 校验验证码是否正确
            if (!code.equals(redisUtils.get(phone).toString())) {
                log.info("------手机号{},验证码错误，当前验证码{}，系统验证码{} ------", phone, code, redisUtils.get(phone));
                return ResultBuildUtil.fail("8648", "验证码错误，请重试！");
            }
            UserLogin user = userService.queryByPhone(phone);
            String userName = user.getUserName();

            String token = UUID.randomUUID().toString();
            userService.saveToken(token, user.getUserId());
            redisUtils.set(token, user.getUserId());

            // 删除redis中的手机验证码
            redisUtils.del(phone);
            // 返回成功的结果
            //data.put("登陆成功,欢迎用户:",userName);
            data.put("token", token);
            data.put("msg", "登陆成功,欢迎用户:" + userName);
            return ResultBuildUtil.success(data);
        }
    }

    /**
     * @author : 190120
     * @date : 2021/8/21 10:16
     * @description : 用于用户登出操作
     */
    @ApiOperation(value = "用户登出", notes = "用于用户登出操作")
    @ApiResponses({
            @ApiResponse(code = 9001, message = "退出失败，token为空"),
            @ApiResponse(code = 9002, message = "token失效，已经退出！")
    })
    @GetMapping("/logOut")
    public RequestResult<String> logOut(HttpServletRequest request) {
        // 获取前端参数token，从redis中删除
        String token = request.getHeader("token");

        // 判断token是否为空
        if (StringUtils.isEmpty(token)) {
            return ResultBuildUtil.fail("9001", "token为空，退出失败！");
        }

        // 判断token是否存在
        if (ObjectUtils.isEmpty(redisUtils.get(token))) {
            return ResultBuildUtil.fail("9002", "token失效，已经退出！");
        }
        // 从redis中删除该token
        redisUtils.del(token);

        // 从数据库中删除该token
        userService.delToken(token);

        // 返回退出成功
        return ResultBuildUtil.success("登出成功！");
    }

    /**
     * @param:
     * @return:
     * @auther: 190120
     * @date: 2021/6/30 0030 9:35
     * 功能描述: 手机号数字校验
     */
    public static boolean isAllNumer(String phone) {
        for (int i = 0; i < phone.length(); i++) {
            if (!Character.isDigit(phone.charAt(i))) {
                return false;
            }
        }
        return true;
    }


    /**
     * @author : 190120
     * @date : 2021/8/21 10:28
     * @description : 修改密码
     */
    @PostMapping("/changePwd")
    @RequestPermission
    @ApiOperation(value = "修改密码", notes = "")
    @ApiResponses({
            @ApiResponse(code = 1002, message = "token错误，重新登录"),
            @ApiResponse(code = 1003, message = "两次密码输入不一致"),
            @ApiResponse(code = 5316, message = "用户未登录！"),
            @ApiResponse(code = 0000, message = "修改密码成功")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "旧密码", required = true),
            @ApiImplicitParam(name = "newPassword", value = "修改密码", required = true),
            @ApiImplicitParam(name = "newPasswordagine", value = "确认密码", required = true)
    })
    public RequestResult<String> modPassword(HttpServletRequest request, @RequestParam String oldPassword, @RequestParam String newPassword, @RequestParam String newPasswordagine) {

        //String token = redisUtils.get("token").toString();
        String token = request.getHeader("token");
        Integer userId = (Integer) redisUtils.get(token);
        if (userId == null) {
            log.info("------ 用户未登录 ------");
            return ResultBuildUtil.fail("5316", "用户未登录！");
        }
        if (newPassword.equals(newPasswordagine)) {
            if (EncodeUtils.testDigest(oldPassword).equals(userService.queryUserEntryById(userId).getUserPassword())) {
                log.info("------ 旧密码输入正确 ------");
                if (oldPassword.equals(newPassword)) {
                    return ResultBuildUtil.fail("2224", "新密码和旧密码一致，修改失败！");
                }
                userService.modPasswordById(userId, EncodeUtils.testDigest(newPassword));
                // 从redis中删除该token
                redisUtils.del(token);

                // 从数据库中删除该token
                userService.delToken(token);
                return ResultBuildUtil.success("密码修改成功！请重新登录");
            } else {
                return ResultBuildUtil.fail("2223", "原密码输入错误！！");
            }
        } else {
            return ResultBuildUtil.fail("1003", "两次密码输入不一致");
        }


    }

    /**
     * @return :
     * @author : 190120
     * @date : 2021/8/2
     * @description :  修改手机号
     */
    @GetMapping("/modPhoneNo")
    @ApiOperation(value = "修改手机号", notes = "根据用户ID修改手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "newPhone", required = true, value = "请填写新手机号"),
            @ApiImplicitParam(name = "verifyCode", required = true, value = "验证码")
    })
    @ApiResponses({
            @ApiResponse(code = 8848, message = "手机号非法，请重新输入"),
            @ApiResponse(code = 8548, message = "该手机已被注册！"),
            @ApiResponse(code = 8648, message = "验证码错误，请重试！"),
            @ApiResponse(code = 8001, message = "手机号验证码未发送，或者已失效！"),
            @ApiResponse(code = 5002, message = "token为空，权限不足，请先登录在进行操作"),
            @ApiResponse(code = 5316, message = "用户未登录！"),
            @ApiResponse(code = 0000, message = "修改成功")
    })
    @RequestPermission
    public RequestResult<String> modPhoneNo(HttpServletRequest request, @RequestParam String newPhone, @RequestParam String verifyCode) {
        //String token = redisUtils.get("token").toString();
        String token = request.getHeader("token");
        Integer userId = (Integer) redisUtils.get(token);
        if (userId == null) {
            log.info("------ 新用户名与旧用户名相同 ------");
            return ResultBuildUtil.fail("5316", "用户未登录！");
        }
        // 校验手机号是否正确
        if (newPhone.length() != 11 || !isAllNumer(newPhone)) {
            return ResultBuildUtil.fail("8848", "手机号非法，请重新输入");
        }
        //判断数据库中是否存在该手机用户
        if (!ObjectUtils.isEmpty(userService.queryByPhone(newPhone))) {
            return ResultBuildUtil.fail("8548", "该手机已被注册！");
        } else {
            if (redisUtils.hasKey(newPhone)) {
                if (verifyCode.equals(redisUtils.get(newPhone).toString())) {
                    userService.modPhoneById(userId, newPhone);

                    // 从redis中删除该token
                    redisUtils.del(token);

                    // 从数据库中删除该token
                    userService.delToken(token);

                    return ResultBuildUtil.success("该用户手机号:" + newPhone + "修改成功，请重新登录");
                } else {
                    return ResultBuildUtil.fail("8648", "验证码错误,请重试");
                }
            } else {
                return ResultBuildUtil.fail("8001", "手机号验证码未发送，或者已失效");
            }
        }
    }

    /**
     * @return :
     * @author : 190120
     * @date : 2021/8/2
     * @description :  修改用户名
     */
    @GetMapping("/modUserName")
    @ApiOperation(value = "修改用户名", notes = "根据用户ID修改用户名")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "newName", required = true, value = "请填写新用户名")
    })

    @ApiResponses({
            @ApiResponse(code = 2181, message = "新用户名和旧用户名一致，修改失败！"),
            @ApiResponse(code = 5002, message = "token为空，权限不足，请先登录在进行操作"),
            @ApiResponse(code = 0000, message = "修改成功"),
            @ApiResponse(code = 5316, message = "用户未登录！")
    })
    @RequestPermission
    public RequestResult<String> modUserName(HttpServletRequest request, @RequestParam String newName) {
        //String token = redisUtils.get("token").toString();
        String token = request.getHeader("token");
        Integer userId = (Integer) redisUtils.get(token);
        if (userId == null) {
            log.info("------ 新用户名与旧用户名相同 ------");
            return ResultBuildUtil.fail("5316", "用户未登录！");
        }
        log.info("userId:{}", userId);
        if (newName.equals(userService.queryUserEntryById(userId).getUserName())) {
            log.info("------ 新用户名与旧用户名相同 ------");
            return ResultBuildUtil.fail("2181", "新用户名和旧用户名一致，修改失败！");
        } else {
            userService.modUserNameById(userId, newName);
            return ResultBuildUtil.success("用户名修改成功，新户名已生效！");
        }
    }

    @GetMapping("/sign")
    @ApiOperation(value = "连续签到", httpMethod = "GET", notes = "每天签到奖励1积分，连续7天签到，奖励20积分，断签从头累积")
    @ApiResponses({
            @ApiResponse(code = 0000, message = "签到成功"),
            @ApiResponse(code = 1001, message = "签到失败"),
            @ApiResponse(code = 1002, message = "今天已经签到完成，明天再来吧"),
            @ApiResponse(code = 5316, message = "用户未登录！")
    })
    @RequestPermission
    public RequestResult<String> Sign(HttpServletRequest request) {
        //String token = (String) redisUtils.get("token");
        String token = request.getHeader("token");
        // 校验token是否有效
        Integer userId = (Integer) redisUtils.get(token);
        if (userId == null) {
            log.info("------ 新用户名与旧用户名相同 ------");
            return ResultBuildUtil.fail("5316", "用户未登录！");
        }
        log.info("------ userId:" + userId);

        // 判断是否首次签到,返回1:首次签到
        if (userService.userSigned(userId) == 1) {
            // 找签到实体
            Sign sign = userService.querySignByUserId(userId);
            // 获取连续签到数量
            Integer countSign = sign.getContinueSign();
            // 添加1积分
            userService.addPoints(userId, 1);
            // 获取用户总积分
            Integer points = userService.queryUserByUserId(userId).getIntegral();
            // 判断是否是第一次签到
            if (countSign == 0) {
                return ResultBuildUtil.success("签到成功,您已连续签到7天，获得额外20积分,当前积分" + points);
            } else {
                return ResultBuildUtil.success("签到成功,您已连续签到" + countSign + "天，积分增加1，,当前积分" + points);
            }
            // 返回2：
        } else if (userService.userSigned(userId) == 2) {
            return ResultBuildUtil.success("今日签到已完成，请明天再来吧");
            // 返回3:签到失败
        } else {
            return ResultBuildUtil.fail("1001", "签到失败");
        }
    }


}
